package com.platform.comm.util;

import com.platform.vo.ExcelCfgDto;
import com.platform.vo.ExcelColCfgDto;
import com.platform.vo.ImportDto;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.Map;
import java.util.Objects;

/**
 * 操作excel常用方法
 * @author Tommy
 */

public class NcExcelTools {
    /**
     * 写excel标题
     * @param sheet          sheet
     * @param config         内容信息
     */
    public static void putTitle(Sheet sheet, ExcelCfgDto config) {
        int colNum = Objects.isNull(config.getFirstColNum())? ExcelCfgDto.DEFAULT_FIRST_COL_NUM : config.getFirstColNum();
        int rowNum = Objects.isNull(config.getTitleRowNum()) ? ExcelCfgDto.DEFAULT_TITLE_ROW_NUM : config.getTitleRowNum();

        Row row = createRow(sheet, rowNum);

        for (int i = 0; i < config.getColumns().size(); i++) {
            ExcelColCfgDto cc = config.getColumns().get(i);
            boolean flag = Objects.isNull(cc) || (Objects.isNull(cc.getTitle()) && Objects.isNull(cc.getFieldName()));
            if (flag) {
                continue;
            }

            Cell cell = createCell(row, colNum + i);

            String title = Objects.isNull(cc.getTitle()) ? cc.getFieldName() : cc.getTitle();
            setCellData(cell, title);
        }
    }

    public static Row createRow(Sheet sheet, int currRowNum){
        Row row = sheet.getRow(currRowNum);
        if (row == null) {
            row = sheet.createRow(currRowNum);
        }

        return row;
    }

    private static Cell createCell(Row row, int colNum){
        Cell cell = row.getCell(colNum);
        if (cell == null) {
            cell = row.createCell(colNum);
        }
        return cell;
    }

    public static void putRow(Row row, ExcelCfgDto config, ImportDto item){

        for (int i = 0; i < config.getColumns().size(); i++) {
            String fieldName = config.getColumns().get(i).getFieldName();
            if (fieldName == null) {
                continue;
            }

            String fieldValue = getFieldValue(item, fieldName);
            int colNum = config.getFirstColNum() + i;

            Cell cell = row.getCell(colNum);
            if (cell == null) {
                cell = row.createCell(i);
            }
            setCellData(cell, fieldValue);
        }
    }

    private static String getFieldValue(ImportDto item, String fieldName){
        Map<String, Object> record = item.getBucket();

        return Objects.toString(record.get(fieldName),"");
    }

    private static void setCellData(Cell cell, String data) {
        if (Objects.isNull(cell)){
            return;
        }
        data = Objects.toString(data, "");
        cell.setCellValue(data);
    }
}
